<template>
  <div id="panel">
    <el-card class="queryForm">
      <el-form
        ref="queryForm"
        :model="queryParams"
        :inline="true"
        :label-position="'right'"
      >
        <!-- 时间选择器 -->
        <el-form-item label="开始时间:" prop="startTime">
          <el-date-picker
            v-model="queryParams.startTime"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 160px"
            @change="checkDuration"
          />
        </el-form-item>
        <el-form-item label="结束时间:" prop="endTime">
          <el-date-picker
            v-model="queryParams.endTime"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 160px"
            @change="checkDuration"
          />
        </el-form-item>
        <!-- 搜索按钮：仅触发查询，不额外校验其他条件 -->
        <el-form-item>
          <el-button type="primary" @click="handleQuery" :loading="loading">
            查询
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 指标切换标签 -->
      <div class="indicator-tabs" v-if="bussinessItemList.length > 0">
        <el-radio-group
          v-model="currentIndicator"
          size="small"
          @change="handleIndicatorChange"
        >
          <el-radio-button
            v-for="item in bussinessItemList"
            :label="item.itemCode"
            :key="item.itemCode"
          >
            {{ item.itemName }}
          </el-radio-button>
        </el-radio-group>
      </div>
    </el-card>

    <!-- 加载状态 -->
    <!-- <div class="loading-container" v-if="loading">
      <el-loading text="正在加载数据..." fullscreen />
    </div> -->

    <!-- 图表区域 -->
    <el-card class="pageContent" >
      <div ref="charA" class="charA" v-if="isChartReady"></div>
      <!-- 空数据提示 -->
      <div class="empty-container" v-else-if="isDataEmpty">
        <el-empty description="暂无数据，请选择其他条件重试"></el-empty>
      </div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { getFactorList } from "@/api/commonApi.js";
import { getWaterQualityComparisonAnalysis } from "@/api/riverGeneralMange/riverGeneralMange.js";

export default {
  name: "HydrologicStation",
  props: ["selTreeId"], // 父组件传递的断面ID（可选，不强制校验）
  data() {
    return {
      loading: false,
      isChartReady: false,
      isDataEmpty: false,
      chartInstance: null,
      currentIndicator: "", // 当前选中指标（可选，不强制校验）
      bussinessItemList: [], // 指标列表

      // 查询参数：默认时间为当月
      queryParams: {
        startTime: this.getDefaultStartTime(),
        endTime: this.getDefaultEndTime(),
        riverid: this.selTreeId || [], // 断面ID（父组件传递，不强制校验）
      },

      // 图表颜色配置
      chartColors: {
        current: "#1890ff",
        monthOnMonth: "#52c41a",
        yearOnYear: "#fa8c16",
      },
    };
  },
  watch: {
    // 断面ID变化时，自动更新参数（不强制触发请求）
    selTreeId: {
      handler(newVal) {
        if (newVal) {
          this.queryParams.riverid = Array.isArray(newVal) ? newVal : [newVal];
        }
      },
      immediate: true,
    },
  },
  created() {
    this.getMonitorFactor(); // 加载指标列表（仅初始化，不强制校验）
  },
  mounted() {
    // 初始化图表实例
    this.$nextTick(() => {
      this.initChartInstance();
      window.addEventListener("resize", this.handleChartResize);
    });
  },
  beforeDestroy() {
    if (this.chartInstance) this.chartInstance.dispose();
    window.removeEventListener("resize", this.handleChartResize);
  },
  methods: {
    // 默认开始时间：当月第一天
    getDefaultStartTime() {
      const now = new Date();
      return new Date(now.getFullYear(), now.getMonth(), 1)
        .toISOString()
        .split("T")[0];
    },

    // 默认结束时间：当月最后一天
    getDefaultEndTime() {
      const now = new Date();
      return new Date(now.getFullYear(), now.getMonth() + 1, 0)
        .toISOString()
        .split("T")[0];
    },

    // 加载指标列表
    getMonitorFactor() {
      getFactorList({ bussinessCategoryCode: "Auto" })
        .then((res) => {
          if (res.data && res.data.length > 0) {
            this.bussinessItemList = res.data;
            this.currentIndicator = res.data[0].itemCode; // 默认选中第一个指标
          }
        })
        .catch((err) => {
          console.error("指标列表加载失败:", err);
          this.$message.error("指标列表加载失败，不影响查询操作");
        });
    },

    // 时间范围校验：仅判断开始时间是否大于结束时间（不阻断查询，仅提示）
    checkDuration() {
      const { startTime, endTime } = this.queryParams;
      if (!startTime || !endTime) return;

      const start = new Date(startTime);
      const end = new Date(endTime);
      if (start > end) {
        this.$message.warning("开始时间不能大于结束时间，请调整");
      }
    },

    // 初始化图表实例
    initChartInstance() {
      this.isChartReady = true;
      const chartDom = this.$refs.charA;
      if (!chartDom) return;

      if (this.chartInstance) this.chartInstance.dispose();
      this.chartInstance = echarts.init(chartDom);
      console.log("图表实例已初始化", this.chartInstance);
      

      // 初始空配置
      this.chartInstance.setOption(
        this.getChartOption({
          xAxis: ["请点击查询获取数据"],
          current: [],
          monthOnMonth: [],
          yearOnYear: [],
        })
      );
    },

    // 生成图表配置项
    getChartOption(data) {
      const { xAxis, current, monthOnMonth, yearOnYear } = data;
      const unit = this.getIndicatorUnit(this.currentIndicator) || "";

      return {
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "shadow" },
          backgroundColor: "rgba(255,255,255,0.9)",
          borderColor: "#e4e7ed",
          borderWidth: 1,
          textStyle: { color: "#303133" },
          formatter: (params) => {
            let html = `${params[0].name}<br/>`;
            params.forEach((item) => {
              html += `${item.marker}${item.seriesName}: ${item.value} ${unit}<br/>`;
            });
            return html;
          },
        },
        legend: {
          data: ["当期", "环比", "同比"],
          top: 10,
          left: "center",
          textStyle: { color: "#606266", fontSize: 12 },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "15%",
          top: "15%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: xAxis,
          axisLabel: {
            rotate: 45,
            color: "#606266",
            fontSize: 12,
            interval: 0,
          },
          axisLine: { lineStyle: { color: "#dcdfe6" } },
          axisTick: { alignWithLabel: true },
        },
        yAxis: {
          type: "value",
          name: unit,
          nameTextStyle: {
            color: "#606266",
            fontSize: 12,
            padding: [0, 0, 0, 40],
          },
          axisLabel: { color: "#606266", fontSize: 12 },
          axisLine: { show: true, lineStyle: { color: "#dcdfe6" } },
          splitLine: { lineStyle: { color: "#f0f0f0", type: "dashed" } },
          min: 0,
          max: this.calcYAxisMax([...current, ...monthOnMonth, ...yearOnYear]),
        },
        series: [
          {
            name: "当期",
            type: "bar",
            data: current,
            itemStyle: { color: this.chartColors.current },
            barWidth: "20%",
            emphasis: {
              focus: "series",
              itemStyle: { shadowBlur: 10, shadowColor: "rgba(0,0,0,0.5)" },
            },
          },
          {
            name: "环比",
            type: "bar",
            data: monthOnMonth,
            itemStyle: { color: this.chartColors.monthOnMonth },
            barWidth: "20%",
            emphasis: {
              focus: "series",
              itemStyle: { shadowBlur: 10, shadowColor: "rgba(0,0,0,0.5)" },
            },
          },
          {
            name: "同比",
            type: "bar",
            data: yearOnYear,
            itemStyle: { color: this.chartColors.yearOnYear },
            barWidth: "20%",
            emphasis: {
              focus: "series",
              itemStyle: { shadowBlur: 10, shadowColor: "rgba(0,0,0,0.5)" },
            },
          },
        ],
        animationEasing: "elasticOut",
      };
    },

    // 计算Y轴最大值（留20%余量）
    calcYAxisMax(data) {
      const validData = data.filter(
        (val) => val !== null && val !== undefined && !isNaN(val)
      );
      return Math.ceil(validData.length ? Math.max(...validData) * 1.2 : 8);
    },

    // 获取指标单位
    getIndicatorUnit(indicatorCode) {
      const indicator = this.bussinessItemList.find(
        (item) => item.itemCode === indicatorCode
      );
      return indicator ? indicator.unit : "";
    },

    // 指标切换：直接触发查询
    handleIndicatorChange() {
      this.handleQuery();
    },

    // 图表自适应
    handleChartResize() {
      if (this.chartInstance) this.chartInstance.resize();
    },

    // 搜索按钮核心逻辑：不额外校验，直接请求数据
    handleQuery() {
      if (!this.chartInstance) {
        this.initChartInstance();
        if (!this.chartInstance) return;
      }
      this.loading = true;
      this.isDataEmpty = false;

      // 构造请求参数（即使参数缺失，也传递给接口）
      const requestParams = {
        segmentId: this.queryParams.riverid.join(","), // 断面ID（空则传空字符串）
        startTime: this.queryParams.startTime || "", // 时间（空则传空字符串）
        endTime: this.queryParams.endTime || "",
        itemId: this.currentIndicator || "", // 指标（空则传空字符串）
      };

      // 发送请求
      getWaterQualityComparisonAnalysis(requestParams)
        .then((res) => {
          this.loading = false;
          const apiData = res.data || {};

          // 处理接口返回数据
          const chartData = {
            xAxis: Array.isArray(apiData.segment) ? apiData.segment : ["暂无数据"],
            current: this.processChartData(apiData.month || []),
            monthOnMonth: this.processChartData(apiData.lastmonth || []),
            yearOnYear: this.processChartData(apiData.lastyear || []),
          };

          // 判断空数据
          this.isDataEmpty =
            chartData.current.every((val) => val === 0) &&
            chartData.monthOnMonth.every((val) => val === 0) &&
            chartData.yearOnYear.every((val) => val === 0);
          // 更新图表
          this.chartInstance.setOption(this.getChartOption(chartData));
        })
        .catch((err) => {
          console.error(err);
          this.loading = false;
          this.isDataEmpty = true;

          // 错误状态下的图表配置
          this.chartInstance.setOption(
            this.getChartOption({
              xAxis: ["数据加载失败"],
              current: [],
              monthOnMonth: [],
              yearOnYear: [],
            })
          );
        });
    },

    // 数据处理：空值转0，字符串转数字
    processChartData(data) {
      return data.map((val) => {
        if (val === null || val === undefined || val === "" || isNaN(val)) {
          return 0;
        }
        return typeof val === "string" ? parseFloat(val) : val;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
#panel {
  padding: 15px;
  min-height: calc(100vh - 40px);

  .queryForm {
    margin-bottom: 15px;
    padding: 10px;
  }

  .pageContent {
    min-height: 600px;
  }

  .charA {
    width: 100%;
    height: 550px;
  }

  .empty-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 550px;
  }

  .indicator-tabs {
    margin-top: 10px;
    overflow-x: auto;
    padding-bottom: 5px;
  }
}
</style>
